package com.sscl.baselibrary.exts

import androidx.annotation.Size
import com.sscl.baselibrary.utils.ConversionUtil.intToHexStr


/**
 * IntExt
 *
 * Int扩展函数
 * @author jackie Penghe
 * @date 2024/9/4
 */


/**
 * 将int转为boolean(0 = false ,1 = true)
 *
 * @return 对应的结果
 */
fun Int.toBoolean(): Boolean {
    return when (this) {
        0 -> false
        1 -> true
        else -> throw RuntimeException("The value $this cannot be converted to Boolean")
    }
}

/**
 * 将一个整数转换成2个字节的byte数组
 *
 * @param i 整数
 * @return 2个字节的byte数组
 */
@Size(2)
fun Int.toByteArrayLength2(): ByteArray {
    val hexString: String = intToHexStr(this)
    val highByte: Byte
    val lowByte: Byte
    val hexStringMinLength = 2
    if (hexString.length > hexStringMinLength) {
        var substring: String = hexString.substring(0, hexString.length - 2)
        highByte = substring.toInt(16).toByte()
        substring = hexString.substring(hexString.length - 2)
        lowByte = substring.toInt(16).toByte()
    } else {
        highByte = 0
        lowByte = hexString.toInt(16).toByte()
    }
    return byteArrayOf(highByte, lowByte)
}

/**
 * 将一个整数转换成4个字节的byte数组
 *
 * @param n 整数
 * @return 4个字节的byte数组
 */
@Size(4)
fun Int.intToByteArrayLength4(): ByteArray {
    val b = ByteArray(4)
    for (i in b.indices) {
        b[i] = ((this ushr (24 - i * 8)) and 0xFF).toByte()
    }
    return b
}

/**
 * 将一个int型的Ip地址转为点分式地址字符串
 *
 * @param ip int型的Ip地址
 * @return 点分式字符串
 */
fun Int.toStringIp4(): String {
    return "${(this shr 24) and 0xFF}.${(this shr 16) and 0xFF}.${(this shr 8) and 0xFF}.${this and 0xFF}"
}

/**
 * 将一个int型的Ip地址转为点分式地址字符串
 *
 * @param ip int型的Ip地址
 * @return 点分式字符串
 */
fun Int.toReverseStringIp4(): String {
    return "${this and 0xFF}.${(this shr 8) and 0xFF}.${(this shr 16) and 0xFF}.${(this shr 24) and 0xFF}"
}

